<?php

namespace Iwester\Http\Controllers\Auth;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use View;
use App;
use Illuminate\Validation\ValidationException;
use Iwester\Http\Model\User\User;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    /**
     * 后台 - 登录表单
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLoginForm(Request $request)
    {
        $redirect = $request->get('redirect', url()->previous());
        return view('iwester::admin.auth.login.login',['redirectUrl'=>$redirect]);
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $redirectUrl = $request->get('redirectUrl', '/');
        $ajax = $request->get('ajax', false);
        //规则验证
        $validator = $this->validateLogin($request->input());
        if ($validator->fails()) {
            return self::failedRedirect($request,$validator->errors()->all());
        }
        // 防止暴力破解，多次登录失败会根据IP锁定
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return self::failedRedirect($request,['登录IP被锁定']);
        }

        //登录验证
        if ($this->attemptLogin($request)) {
            $checkDel = $this->guard()->attempt(
                [ 'username' => $request->input('username'), 'password' => $request->input('password') , 'is_delete'=> 1], $request->has('remember')
            );
            if ($checkDel){
                \Auth::logout();
                return self::failedRedirect($request, ['账号被冻结']);
            }
            return $this->redirectTo($ajax);
        }

        // 登录失败，失败次数++，防止暴力破解
        $this->incrementLoginAttempts($request);
        return self::failedRedirect($request,['用户名密码错误']);
    }

    protected static function failedRedirect($request, $errorsMsg){
        $ajax = $request->get('ajax', false);
        if ($ajax){
            return ['code'=> 201, 'message'=> $errorsMsg[0]];
        }else{
            return  redirect()->route('admin.loginForm')->with('errors', $errorsMsg)->with('old_username',$request->input('username'));
        }
    }


    //登陆验证
    protected function attemptLogin(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        // 用户名登录方式
        $usernameLogin = $this->guard()->attempt(
            [ 'username' => $username, 'password' => $password], $request->has('remember')
        );
        if ($usernameLogin) {
            return true;
        }
        // 验证手机号登录方式
        $mobileLogin = $this->guard()->attempt(
            [ 'email' => $username, 'password' => $password], $request->has('remember')
        );
        if ($mobileLogin) {
            return true;
        }
        return false;
    }


    //登录页面验证
    protected function validateLogin($data)
    {
        return \Illuminate\Support\Facades\Validator::make($data, [
            'username'     => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute为必填项',
            'min'      => ':attribute长度不符合要求'
        ], [
            'username'     => '用户名',
            'password' => '密码'
        ]);
    }

    /**
     * 用于登录的字段
     * @return string
     */
    public function username()
    {
        return 'username';
    }

    /**
     * 登录成功后的跳转地址
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function redirectTo($ajax = false)
    {
        if ($ajax){
            return ['code'=> 200, 'message', '登录成功'];
        }else{
            return redirect()->route('admin.layout');
        }
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $redirectUrl = $request->get('redirectUrl', false);
        $this->guard()->logout();

        $request->session()->invalidate();

        return $redirectUrl ? redirect($redirectUrl) : redirect(route('admin.login'));
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }

}
